import { useParams, useNavigate, Link } from 'react-router-dom';
import { ArrowLeft, Edit, Trash2, ChevronLeft, ChevronRight, Calendar, Tag, FileText } from 'lucide-react';
import { useDiaryStore } from '../store/diaryStore';
import { TagBadge } from '../components/TagBadge';
import { format } from 'date-fns';
import { toast } from 'sonner';

const moods = [
  { value: 'happy', label: 'Happy', emoji: '😊' },
  { value: 'sad', label: 'Sad', emoji: '😢' },
  { value: 'excited', label: 'Excited', emoji: '🤩' },
  { value: 'calm', label: 'Calm', emoji: '😌' },
  { value: 'anxious', label: 'Anxious', emoji: '😰' },
  { value: 'grateful', label: 'Grateful', emoji: '🙏' },
  { value: 'thoughtful', label: 'Thoughtful', emoji: '🤔' },
  { value: 'energetic', label: 'Energetic', emoji: '⚡' },
];

export default function EntryDetail() {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const { entries, getEntryById, deleteEntry, toggleTag, getTemplateById } = useDiaryStore();
  
  if (!id) {
    navigate('/entries');
    return null;
  }
  
  const entry = getEntryById(id);
  
  if (!entry) {
    return (
      <div className="max-w-4xl mx-auto">
        <div className="card text-center py-12">
          <h2 className="text-xl font-inter font-semibold text-forest-green mb-2">
            Entry Not Found
          </h2>
          <p className="text-warm-gray mb-6">
            The entry you're looking for doesn't exist or may have been deleted.
          </p>
          <Link to="/entries" className="btn-primary">
            Back to Entries
          </Link>
        </div>
      </div>
    );
  }
  
  // Find previous and next entries
  const currentIndex = entries.findIndex(e => e.id === id);
  const previousEntry = currentIndex < entries.length - 1 ? entries[currentIndex + 1] : null;
  const nextEntry = currentIndex > 0 ? entries[currentIndex - 1] : null;
  
  const handleDelete = () => {
    if (window.confirm('Are you sure you want to delete this entry? This action cannot be undone.')) {
      deleteEntry(id);
      toast.success('Entry deleted successfully');
      navigate('/entries');
    }
  };
  
  const formatEntryDate = (dateString: string) => {
    try {
      return format(new Date(dateString), 'EEEE, MMMM do, yyyy');
    } catch {
      return dateString;
    }
  };
  
  const formatCreatedDate = (dateString: string) => {
    try {
      return format(new Date(dateString), 'MMM dd, yyyy \'at\' h:mm a');
    } catch {
      return dateString;
    }
  };
  
  const getMoodData = (mood: string) => {
    return moods.find(m => m.value === mood);
  };
  
  const moodData = getMoodData(entry.mood);
  const wordCount = entry.content.replace(/<[^>]*>/g, '').split(/\s+/).filter(word => word.length > 0).length;

  return (
    <div className="max-w-4xl mx-auto">
      {/* Header */}
      <div className="flex items-center justify-between mb-8">
        <button
          onClick={() => navigate(-1)}
          className="flex items-center gap-2 text-sage hover:text-forest-green transition-colors"
        >
          <ArrowLeft size={20} />
          Back
        </button>
        
        <div className="flex items-center gap-3">
          <Link
            to={`/write/${entry.id}`}
            className="btn-secondary flex items-center gap-2"
          >
            <Edit size={16} />
            Edit
          </Link>
          
          <button
            onClick={handleDelete}
            className="flex items-center gap-2 px-4 py-2 text-red-600 border border-red-200 rounded-lg hover:bg-red-50 transition-colors"
          >
            <Trash2 size={16} />
            Delete
          </button>
        </div>
      </div>
      
      {/* Entry Content */}
      <article className="card mb-8">
        {/* Entry Header */}
        <header className="mb-6 pb-6 border-b border-gray-200">
          <h1 className="text-3xl font-inter font-bold text-forest-green mb-4">
            {entry.title || 'Untitled Entry'}
          </h1>
          
          <div className="flex flex-wrap items-center gap-6 text-sm text-warm-gray mb-4">
            <div className="flex items-center gap-2">
              <Calendar size={16} />
              <span>{formatEntryDate(entry.date)}</span>
            </div>
            
            {moodData && (
              <div className="flex items-center gap-2">
                <span className="text-lg">{moodData.emoji}</span>
                <span>Feeling {moodData.label}</span>
              </div>
            )}
            
            <div>
              <span>{wordCount} {wordCount === 1 ? 'word' : 'words'}</span>
            </div>
            
            {entry.templateId && (() => {
              const template = getTemplateById(entry.templateId);
              return template ? (
                <div className="flex items-center gap-2">
                  <FileText size={16} />
                  <span>Template: <span className="text-forest-green font-medium">{template.name}</span></span>
                </div>
              ) : null;
            })()}
          </div>
          
          {/* Tags */}
          {entry.tags && entry.tags.length > 0 && (
            <div className="flex items-start gap-3">
              <div className="flex items-center gap-2 text-sm text-warm-gray mt-1">
                <Tag size={16} />
                <span>Tags:</span>
              </div>
              <div className="flex flex-wrap gap-2">
                {entry.tags.map((tag) => (
                  <TagBadge
                    key={tag}
                    tag={tag}
                    onClick={() => {
                      toggleTag(tag);
                      navigate('/entries');
                    }}
                    interactive
                    size="md"
                  />
                ))}
              </div>
            </div>
          )}
        </header>
        
        {/* Entry Body */}
        {entry.templateId && entry.templateSections ? (
          <div className="space-y-6">
            {(() => {
              const template = getTemplateById(entry.templateId!);
              if (!template) {
                return (
                  <div 
                    className="prose prose-lg max-w-none text-warm-gray leading-relaxed"
                    dangerouslySetInnerHTML={{ __html: entry.content }}
                  />
                );
              }
              
              // Sort sections by order
              const sortedSections = template.sections.sort((a, b) => a.order - b.order);
              
              return sortedSections.map((section) => {
                const sectionContent = entry.templateSections![section.id];
                if (!sectionContent || sectionContent.trim() === '') {
                  return null;
                }
                
                return (
                  <div key={section.id} className="template-section">
                    <h3 className="text-lg font-inter font-semibold text-forest-green mb-3 flex items-center gap-2">
                      <span className="w-1 h-6 bg-sage rounded-full"></span>
                      {section.title}
                    </h3>
                    <div className="ml-5 pl-4 border-l-2 border-gray-100">
                      <div 
                        className="prose prose-base max-w-none text-warm-gray leading-relaxed"
                        dangerouslySetInnerHTML={{ __html: sectionContent }}
                      />
                    </div>
                  </div>
                );
              });
            })()
            }
          </div>
        ) : (
          <div 
            className="prose prose-lg max-w-none text-warm-gray leading-relaxed"
            dangerouslySetInnerHTML={{ __html: entry.content }}
          />
        )}
        
        {/* Entry Footer */}
        <footer className="mt-8 pt-6 border-t border-gray-200 text-sm text-sage">
          <div className="flex items-center justify-between">
            <div>
              Created on {formatCreatedDate(entry.createdAt)}
            </div>
            {entry.updatedAt !== entry.createdAt && (
              <div>
                Last updated on {formatCreatedDate(entry.updatedAt)}
              </div>
            )}
          </div>
        </footer>
      </article>
      
      {/* Navigation */}
      <div className="flex items-center justify-between">
        <div className="flex-1">
          {previousEntry && (
            <Link
              to={`/entry/${previousEntry.id}`}
              className="flex items-center gap-3 p-4 bg-white rounded-lg border border-gray-200 hover:border-sage hover:shadow-md transition-all duration-200 max-w-sm"
            >
              <ChevronLeft className="text-sage flex-shrink-0" size={20} />
              <div className="min-w-0">
                <p className="text-xs text-sage mb-1">Previous Entry</p>
                <p className="font-medium text-forest-green truncate">
                  {previousEntry.title || 'Untitled Entry'}
                </p>
                <p className="text-xs text-warm-gray">
                  {format(new Date(previousEntry.date), 'MMM dd, yyyy')}
                </p>
              </div>
            </Link>
          )}
        </div>
        
        <div className="flex-1 flex justify-end">
          {nextEntry && (
            <Link
              to={`/entry/${nextEntry.id}`}
              className="flex items-center gap-3 p-4 bg-white rounded-lg border border-gray-200 hover:border-sage hover:shadow-md transition-all duration-200 max-w-sm"
            >
              <div className="min-w-0 text-right">
                <p className="text-xs text-sage mb-1">Next Entry</p>
                <p className="font-medium text-forest-green truncate">
                  {nextEntry.title || 'Untitled Entry'}
                </p>
                <p className="text-xs text-warm-gray">
                  {format(new Date(nextEntry.date), 'MMM dd, yyyy')}
                </p>
              </div>
              <ChevronRight className="text-sage flex-shrink-0" size={20} />
            </Link>
          )}
        </div>
      </div>
    </div>
  );
}